﻿
using System.Security.Cryptography;

namespace Timo.Common.Extension;

/// <summary>
/// sha1加密
/// </summary>
public static class SHA1EncryptHelper
{
    private static string default_key { get; set; } = "a2023?01";

    /// <summary>
    /// sha1加密
    /// </summary>
    /// <param name="str">待加密的字符串</param>
    /// <returns></returns>
    public static string SHA1Encrypt(this string str)
    {
        //创建SHA1加密算法对象
        SHA1 sha1 = SHA1.Create();
        //将原始密码转换为字节数组
        byte[] originalPwd = Encoding.UTF8.GetBytes(str);
        //执行加密
        byte[] encryPwd = sha1.ComputeHash(originalPwd);
        //将加密后的字节数组转换为大写字符串
        return string.Join("", encryPwd.Select(b => string.Format("{0:x2}",b)).ToArray());
    }

    /// <summary>  
    /// SHA1文件流加密
    /// </summary>  
    /// <param name="input">文件流</param>
    /// <returns>返回40位大写字符串</returns>  
    public static string SHA1StreamEncrypt(this Stream stream)
    {
        string res = string.Empty;
        if (stream == null || stream == default(Stream))
            return res;
        try
        {
            using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
            {
                
                byte[] btOut = sha1.ComputeHash(stream);
                for (int i = 0; i < btOut.Length; i++)
                {
                    res += btOut[i].ToString("x2");
                }
                return res;
            }
        }
        catch
        {
        }
        return res;
    }

    /// <summary>
    /// HMAC1 公钥加密
    /// </summary>
    /// <param name="str">待加密字符串</param>
    /// <param name="publickey">公钥</param>
    /// <returns></returns>
    public static string HMAC1Encrypt(this string str, string? publickey = null)
    {
        var res = string.Empty;
        if (string.IsNullOrEmpty(str) || string.IsNullOrWhiteSpace(str))
            return res;
        if (string.IsNullOrEmpty(publickey) || string.IsNullOrWhiteSpace(publickey))
            publickey = default_key;
        byte[] byte1 = System.Text.Encoding.UTF8.GetBytes(publickey);
        byte[] byte2 = System.Text.Encoding.UTF8.GetBytes(str);
        HMACSHA1 hmac = new HMACSHA1(byte1);

        //把比特流连接起来，附加到字符串里面。
        //比特流转化字符串万能linq：.Aggregate("", (s, e) => s + String.Format("{0:x2}", e), s => s)
        res = hmac.ComputeHash(byte2).Aggregate("", (s, e) => s + String.Format("{0:x2}", e), s => s);
        return res;
    }

}
